package com.clsz.service.impl;

import com.clsz.annotation.RedisCache;
import com.clsz.bean.bo.FilmSearchBo;
import com.clsz.bean.po.Comment;
import com.clsz.bean.po.FilmInfo;
import com.clsz.mapper.FilmMapper;
import com.clsz.service.FilmService;
import com.clsz.utils.ESResponse;
import com.clsz.utils.ESUtils;
import com.clsz.utils.RedisUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class FilmServiceImpl implements FilmService {
    @Resource
    private FilmMapper filmMapper;
    @Resource
    private RedisUtils redisUtils;
    @Resource
    private ESUtils esUtils;

    @Override
    @RedisCache(duration = 60*10)
    public List<FilmInfo> getListByTypeId(Integer typeId) {
//        //1.判断redis中是否有缓存
//        //1.1缓存数据的key:包名.类名.方法名（形参列表）
//        //实例化map对象，装箱key
//        Map<String, Object> keyMap = new HashMap<>();
//        keyMap.put("method", "com.clsz.service.impl.getListByTypeId");
//        keyMap.put("params", new Object[]{typeId});
//        //对map对象使用json序列化为key字符串
//        String key ="Cache-"+JSON.toJSONString(keyMap);
//        if (redisUtils.get(key)!=null) {
//            System.out.println("取缓存");
//            return (List<FilmInfo>) redisUtils.get(key);
//        }
        List<FilmInfo> value = filmMapper.selectListByTypeId(typeId);
//        redisUtils.set(key, value,60*10);
        return value;
    }

    @Override
    @RedisCache(duration = 60*10)
    public Integer getCountByTypeId(Integer typeId) {
        Integer value = filmMapper.selectCountByTypeId(typeId);
        return value;
    }

    @Override
    @RedisCache(duration = 60*10)
    public List<FilmInfo> selectListOrderBy(String column) {
        List<FilmInfo> value = filmMapper.selectListOrderBy(column);
        return value;
    }

    /**
     *es条件查询
     * @param bo
     * @return
     */
    @Override
    @RedisCache(duration = 60*10)
    public List<FilmInfo> searchList(FilmSearchBo bo) {
        //实例化资源查询构建器
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        //实例化逻辑查询构建起
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        //2.1添加影片类型筛选条件  must():&& should():||
        //termQuery():与存储原文档进行匹配   matchQuery():与索引词条进行匹配
        if (bo.getCategoryId() != null) {
            boolQueryBuilder.must(QueryBuilders.matchQuery("film_cate_query",bo.getCategoryId()));
        }
        //2.2 添加拍摄地筛选条件
        if (bo.getRegionId() != null) {
            boolQueryBuilder.must(QueryBuilders.matchQuery("film_region_query", bo.getRegionId()));
        }
        //2.3添加影片上映年代筛选条件
        if (bo.getYear() != null && !bo.getYear().isBlank()) {
            boolQueryBuilder.must(QueryBuilders.termQuery("film_years", bo.getYear()));
        }
        //2.4 关键字筛选条件
        if (bo.getKeyword() != null && !bo.getKeyword().isBlank()) {
            boolQueryBuilder.must(QueryBuilders.matchQuery("film_name", bo.getKeyword()));
//            boolQueryBuilder.must(QueryBuilders.matchQuery("film_real_name", bo.getKeyword()));
        }
        //3将逻辑查询构建器添加到资源查询构建器
        searchSourceBuilder.query(boolQueryBuilder);
        if (bo.getOrderColumn() != null && !bo.getOrderColumn().isBlank()) {
            searchSourceBuilder.sort(
                    bo.getOrderColumn(),
                    bo.getOrderType() != null && bo.getOrderType().equalsIgnoreCase("desc") ? SortOrder.DESC : SortOrder.ASC
            );
        }
        //4.配置分页条件
        searchSourceBuilder.from(bo.getStartIndex());
        searchSourceBuilder.size(bo.getPageSize());
        //5.发送查询请求得到响应
        ESResponse<FilmInfo> filmList = esUtils.search("film", searchSourceBuilder, FilmInfo.class);
        //6.将查询结果进行映射
        bo.setResultCount((int)filmList.getResCount());
        //7.返回满足条件的文档
        return filmList.getData();
    }

    /**
     * es查找一个电影
     * @param filmId
     */
    @Override
    public FilmInfo searchOne(Integer filmId) {
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        boolQueryBuilder.must(QueryBuilders.termQuery("film_id", filmId));
        searchSourceBuilder.query(boolQueryBuilder);
        ESResponse<FilmInfo> filmList = esUtils.search("film", searchSourceBuilder, FilmInfo.class);
        return filmList.getData().size()==1?filmList.getData().get(0) : null;
    }

    /**
     * 查找影评
     * @param filmId
     * @return
     */
    @Override
    public List<Comment> getComment(Integer filmId) {
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        boolQueryBuilder.must(QueryBuilders.termQuery("film_id", filmId));
        searchSourceBuilder.query(boolQueryBuilder);
        searchSourceBuilder.sort("cmmt_createtime", SortOrder.DESC);
        searchSourceBuilder.from(0);
        searchSourceBuilder.size(20);
        ESResponse<Comment> commentList = esUtils.search("comment", searchSourceBuilder, Comment.class);
        return commentList.getData();
    }

}
